from typing import List, Dict, Any, Literal
from db.operations import BaseOperations


class UserBookshelfOperations(BaseOperations):
    """用户书架数据库操作类"""

    def __init__(self):
        # 继承BaseOperations，指定表名为user_bookshelf
        super().__init__("user_bookshelf")

    async def batch_insert_bookshelf_items(
        self,
        bookshelf_data: List[Dict[str, Any]],
        on_duplicate: Literal["skip", "update"] = "skip",
    ) -> int:
        """
        批量插入用户书架数据

        Args:
            bookshelf_data (List[Dict[str, Any]]): 书架数据列表
            每个字典应包含书架项的字段，例如：
            {
                "user_id": 1,
                "book_id": 123,
                "add_at": 1686825600  # 时间戳
            }
            on_duplicate (str): 重复处理策略 - "skip"(跳过), "update"(更新)

        Returns:
            int: 成功插入的书架项数量
        """
        if not bookshelf_data:
            return 0

        # 调用父类的批量插入方法
        return await self.batch_insert(bookshelf_data, on_duplicate=on_duplicate)

    async def batch_delete_bookshelf_items(
        self, user_book_pairs: List[Dict[str, int]]
    ) -> int:
        """
        批量删除用户书架项

        Args:
            user_book_pairs (List[Dict[str, int]]): 用户ID和图书ID对列表
            每个字典应包含：
            {
                "user_id": 1,
                "book_id": 123
            }

        Returns:
            int: 成功删除的书架项数量
        """
        if not user_book_pairs:
            return 0

        # 调用父类的批量删除方法
        return await self.batch_delete(where_conditions=user_book_pairs)

    async def batch_query_user_bookshelf(
        self, user_id: int, order_by: str = "add_at DESC"
    ) -> List[Dict[str, Any]]:
        """
        查询指定用户的书架

        Args:
            user_id (int): 用户ID
            order_by (str): 排序子句，默认按添加时间倒序排列

        Returns:
            List[Dict[str, Any]]: 用户书架列表
            每个字典包含：
            {
                "user_id": 1,
                "book_id": 123,
                "add_at": 1686825600
            }
        """
        where_clause = "user_id = %s"
        params = (user_id,)

        return await self.batch_query(
            where_clause=where_clause, params=params, order_by=order_by
        )
